const db = require('../db');

const membersService = {
    create: async (
        surname,
        name,
        lastName,
        dateOfBirth
    ) => {
        const rows = await db.query(
            `
                INSERT INTO "member" ("surname", "name", "lastName", "dateOfBirth")
                VALUES
                (
                    ?,
                    ?,
                    ?,
                    date(?)
                )
                RETURNING *
            `,
            [
                surname,
                name,
                lastName,
                dateOfBirth
            ]
        );

        const user = rows[0];

        db.query(
            `
                INSERT INTO "active_member"
                VALUES (?)
            `,
            [
                user.id
            ]
        );

        return rows;
    },

    getAll: () => db.query(
        `
            SELECT *
            FROM "member"
            WHERE "id" IN (
                SELECT "id"
                FROM "active_member"
            )
            ORDER BY "surname", "name", "lastName"
        `
    ),

    delete: (memberId) => db.query(
        `
            DELETE FROM "active_member"
            WHERE id = ?
            RETURNING *
        `,
        [ memberId ]
    )
};

module.exports = membersService;
